//
//  WXImagePickerModule.m
//  XYLib
//
//  Created by Richard on 2019/3/7.
//  Copyright © 2019年 XY. All rights reserved.
//
#define KScreenWidth  [UIScreen mainScreen].bounds.size.width
#define KScreenHeight  [UIScreen mainScreen].bounds.size.height

#import <AssetsLibrary/AssetsLibrary.h>
#import "WXImagePickerModule.h"
#import <AVFoundation/AVCaptureDevice.h>
#import "UIImage+Color.h"

BOOL isPhotoSelect = NO;

@interface WXImagePickerModule()
//@property (nonatomic,assign) CGFloat cropWidth;
//@property (nonatomic,assign) CGFloat cropHeight;
@property(nonatomic,copy)WXModuleCallback callback;
@end

@implementation WXImagePickerModule
@synthesize weexInstance;
WX_EXPORT_METHOD(@selector(takePhoto:))
//WX_EXPORT_METHOD(@selector(setCropWidth:height:))
    
//- (void)setCropWidth:(CGFloat)width height:(CGFloat)height {
//    self.cropWidth = width;
//    self.cropHeight = height;
//}

-(BOOL)isPhotoLibraryAvailable
{
    return [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary];
}

-(void)takePhoto:(WXModuleCallback)callback
{
    ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus];
    if (status == ALAuthorizationStatusRestricted || status ==ALAuthorizationStatusDenied){
        //无权限
        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"未获得授权访问相册" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去设置", nil];
        [alertView show];
        return;
    }
    
    self.callback = callback;
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
//    imagePicker.modalPresentationStyle = UIModalPresentationCustom;
    imagePicker.modalPresentationStyle = UIModalPresentationCurrentContext;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.delegate = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        UIViewController *root = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
        while (root.presentedViewController != nil) {
            root = root.presentedViewController;
        }
        [root presentViewController:imagePicker animated:YES completion:nil];
    });
//    [self.weexInstance.viewController.navigationController presentViewController:imagePicker animated:YES completion:nil];
    imagePicker = nil;
    isPhotoSelect = NO;
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info{
    
    if (!isPhotoSelect) {
        isPhotoSelect = YES;
        UIImage *orgImage = info[UIImagePickerControllerOriginalImage];
        orgImage = [UIImage imageFixOrientation:orgImage];

    //    if (self.cropWidth && self.cropHeight) {
    //        orgImage = [self cropImage:orgImage];
    //    }

        NSString*name = [NSString stringWithFormat:@"%u.png",arc4random()];
        NSString *fullPath = [NSTemporaryDirectory() stringByAppendingPathComponent:name];
         [UIImagePNGRepresentation(orgImage) writeToFile:fullPath atomically:YES];
        
        NSData *fileImageData = UIImageJPEGRepresentation(orgImage, 0.5);
        NSString *pictureDataString=[fileImageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        
        if (self.callback) {
            NSDictionary* dic =@{ @"result": @"success",@"path":fullPath,@"file":pictureDataString};
            self.callback(dic);
        }
//        [picker dismissViewControllerAnimated:NO completion:nil];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [picker dismissViewControllerAnimated:YES completion:nil];
    });
}

// 以图片中心为中心,裁剪图片
//-(UIImage *)cropImage:(UIImage *)image{
//
//    CGImageRef sourceImageRef = [image CGImage];// 将UIImage转换成CGImageRef
//
//    CGFloat _imageWidth = image.size.width * image.scale;
//    CGFloat _imageHeight = image.size.height * image.scale;
//
//    CGFloat  width = _imageWidth * self.cropWidth / KScreenWidth;
//    CGFloat  height = _imageWidth * self.cropHeight / KScreenHeight;
//
//    CGRect rect = CGRectMake((_imageWidth - width)/2, (_imageHeight - height)/2, width, height);
//    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect);//按照给定的矩形区域进行剪裁
//    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
//
//    return newImage;
//}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    dispatch_async(dispatch_get_main_queue(), ^{
        [picker dismissViewControllerAnimated:YES completion:^{
            NSDictionary* dic =@{ @"result": @"cancel"};
            self.callback(dic);
        }];
    });
//    if (self.callback) {
//        NSDictionary* dic =@{ @"result": @"cancel"};
//        self.callback(dic);
//    }
//     [picker dismissViewControllerAnimated:NO completion:nil];
}

#pragma mark - ActionSheet Delegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 2) {
        return;
    }
    
    if (buttonIndex == 0) {
        ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
        if (author == ALAuthorizationStatusRestricted || author ==ALAuthorizationStatusDenied){
            //无权限
            UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"未获得授权访问相册" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去设置", nil];
            [alertView show];
            return;
        }
    }else if (buttonIndex == 1) {
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
        {
            //无权限
            UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"未获得授权使用摄像头" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去设置", nil];
            [alertView show];
            return;
        }
    }
    
    
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate      = self;
    imagePicker.allowsEditing = YES;
    if (buttonIndex == 0) {
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    } else {
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    [self.weexInstance.viewController.navigationController presentViewController:imagePicker animated:YES completion:nil];
    
}

#pragma mark - UIAlertView Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }
}

@end
